package com.sxhuayuan.parking.controller.member;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.shiro.AccountType;
import com.sxhuayuan.parking.compenent.shiro.AuthenticationToken;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.entity.Member;
import com.sxhuayuan.parking.plugin.payment.WxPayPlugin;
import com.sxhuayuan.parking.service.MemberCarPlateService;
import com.sxhuayuan.parking.service.MemberService;
import com.sxhuayuan.parking.service.MonthCardOrderService;
import com.sxhuayuan.parking.service.OrderService;
import com.sxhuayuan.parking.service.ParkChannelService;
import com.sxhuayuan.parking.service.ParkingLotService;
import com.sxhuayuan.parking.service.PluginService;

import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.Jscode2sessionResult;
import weixin.popular.bean.wxa.WxaDUserInfo;
import weixin.popular.util.WxaUtil;

/**
 * 小程序相关操作
 * 
 * @author gy
 *
 */
@RestController("memberMiniController")
@RequestMapping("/member/mini")
public class MiniController extends BaseController {

	private Logger log = LoggerFactory.getLogger(MiniController.class);

	@Autowired
	MemberService memberService;
	@Autowired
	MemberCarPlateService memberCarPlateService;
	@Autowired
	OrderService orderService;
	@Autowired
	WxPayPlugin wxpayPlugin;
	@Autowired
	ParkingLotService parkingLotService;
	@Autowired
	ParkChannelService exitService;
	@Autowired
	MonthCardOrderService monthCardOrderService;
	@Autowired
	PluginService pluginService;

	// 小程序的appid
	@Value("${wechat.small_program.appId}")
	private String appId;
	// 小程序appSecret
	@Value("${wechat.small_program.appSecret}")
	private String appSecret;

	/**
	 * 微信小程序登录返回sessionId
	 * 
	 * @param code
	 * @param request
	 * @return
	 */
	@GetMapping("/wxlogin/{code}")
	public RespMessage login(@PathVariable String code, String iv, String enc, HttpServletRequest request) {
		// {"openid":"op-Cl5FvLjCHlqpoeBH0Dt_YDyd4","session_key":"bCmVKl76QAVIgVyLpdKlww=="}
		// {"errcode":40029,"errmsg":"invalid code, hints: [ req_id: pFHBO6yFe-V4r ]"}
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		log.debug("uri={}, subject: {}, session={}", request.getRequestURI(), subject, session.getId());

		if (!subject.isAuthenticated()) {

			// JSONObject jsonObject = WXAppletUserInfo.getSessionKeyOropenid(code);
			// String openid = jsonObject.getString("openid");

			Jscode2sessionResult jscode2sessionResult = SnsAPI.jscode2session(appId, appSecret, code);
			String openid = jscode2sessionResult.getOpenid();

			if (jscode2sessionResult != null && jscode2sessionResult.isSuccess()) {

				String sessionKey = jscode2sessionResult.getSession_key();

				// 缓存session_key
				cacheInSession(request.getSession(), WX_SESSION_KEY, sessionKey);

				WxaDUserInfo userInfo = null;
				if (StringUtils.isNotEmpty(enc) && StringUtils.isNotEmpty(iv)) {
					userInfo = WxaUtil.decryptUserInfo(sessionKey, enc, iv);
					if (userInfo == null) {
						return RespMessage.error(Message.WEIXIN_GET_USERINFO_FAIL);
					}
				}

				Member member = memberService.findByOpenId(openid);

				if (member == null) {
					member = new Member();
					// member.setAppid(appid);
					member.setOpenid(openid);
					member.setUnionid(jscode2sessionResult.getUnionid());
					member.setPlatform(getPlatform(request));
					if (userInfo != null) {
						member.setCity(userInfo.getCity());
						member.setCountry(userInfo.getCountry());
						member.setGender(Member.Gender.fromWx(Integer.valueOf(userInfo.getGender())));
						member.setHeadimg(userInfo.getAvatarUrl());
						member.setNickname(userInfo.getNickName());
						member.setProvince(userInfo.getProvince());
						member.setUnionid(userInfo.getUnionId());
					}
					memberService.save(member);
				}

				AuthenticationToken token = new AuthenticationToken(AccountType.member, member.getId() + "@@" + member.getOpenid(), member.getOpenid(), null, null, false, null);
				Subject login = SecurityUtils.getSecurityManager().login(subject, token);
				return RespMessage.builder().success().setDatas(login.getSession().getId()).build();

			} else {
				return RespMessage.error(RespMessage.Status.ERROR, "errcode:" + jscode2sessionResult.getErrcode() + ", errmsg:" + jscode2sessionResult.getErrmsg());
			}

		} else {
			return RespMessage.builder().success().setDatas(subject.getSession().getId()).build();
		}

	}

	/** 测试退出登录接口 */
	@GetMapping("/logout")
	public RespMessage logout() {
		System.out.println(SecurityUtils.getSubject().getSession().getId());
		SecurityUtils.getSubject().logout();
		return RespMessage.success();
	}

}
